package com.rickpan.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rickpan.dto.zhipuai.ZhipuAIRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

/**
 * 智谱AI API客户端
 */
@Component
public class ZhipuAIClient {

    private static final Logger log = LoggerFactory.getLogger(ZhipuAIClient.class);
    private static final String ZHIPUAI_API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送请求到智谱AI（非流式）
     * @param apiKey API密钥
     * @param request 请求对象
     * @return 响应内容
     */
    public String sendRequest(String apiKey, ZhipuAIRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("Content-Type", "application/json");

        try {
            HttpEntity<ZhipuAIRequest> entity = new HttpEntity<>(request, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    ZHIPUAI_API_URL, HttpMethod.POST, entity, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                return parseResponse(response.getBody());
            } else {
                throw new RuntimeException("智谱AI API调用失败: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("Error in ZhipuAI request: {}", e.getMessage(), e);
            
            // 特殊处理429错误（限额超出）
            if (e.getMessage() != null && e.getMessage().contains("429")) {
                throw new RuntimeException("API调用限额已用完，请稍后重试", e);
            }
            
            throw new RuntimeException("智谱AI API调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 测试API Key是否有效
     * @param apiKey API密钥
     * @return 是否有效
     */
    public boolean testApiKey(String apiKey) {
        try {
            // 创建简单的测试请求
            ZhipuAIRequest testRequest = ZhipuAIRequest.builder()
                    .model("glm-4-flash-250414")
                    .temperature(0.9)
                    .maxTokens(10)
                    .addMessage("user", "Hello")
                    .build();

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("Content-Type", "application/json");

            HttpEntity<ZhipuAIRequest> entity = new HttpEntity<>(testRequest, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    ZHIPUAI_API_URL, HttpMethod.POST, entity, String.class);

            return response.getStatusCode().is2xxSuccessful();
        } catch (Exception e) {
            log.warn("ZhipuAI API Key test failed: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 解析智谱AI响应，提取消息内容
     * @param responseBody 响应体
     * @return 消息内容
     */
    private String parseResponse(String responseBody) {
        try {
            JsonNode jsonNode = objectMapper.readTree(responseBody);
            JsonNode choices = jsonNode.get("choices");
            if (choices != null && choices.isArray() && choices.size() > 0) {
                JsonNode message = choices.get(0).get("message");
                if (message != null && message.has("content")) {
                    return message.get("content").asText();
                }
            }
            return "解析响应失败";
        } catch (Exception e) {
            log.error("Error parsing ZhipuAI response: {}", e.getMessage());
            return "解析响应失败: " + e.getMessage();
        }
    }
}
